package com.example.javabase.ScriptEngineManager;

import org.apache.commons.jexl3.*;
import org.apache.commons.jexl3.internal.Engine;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author: wyb
 * @date: 2021/11/3 14:38
 * @describe:
 * @vision 1.0
 */
public class ExpUtil {

    /**
     *  动态表达式计算
     * @param eval 表达式不能有汉字
     * @param map
     * @param clazz
     * @Description: 根据表达式和参数集合进行计算
     * @Author: fearless
     * @Date: 2021/6/22 16:12
     * @return: java.lang.Object
     */
    private static Object executeExpression(String eval, Map<String, Object> map, Class<?>... clazz) {
        JexlExpression expression = new Engine().createExpression(eval);
        JexlContext context = new MapContext();
        Arrays.asList(clazz).forEach(cal -> {
            context.set(cal.getSimpleName(),cal);
        });
        if (Objects.nonNull(map)) {
            map.forEach(context::set);
        }
        return expression.evaluate(context);
    }


    /**
     *  支持条件表达式计算
     * @param eval 表达式不能有汉字（支持条件语句的表达式）
     * @param map
     * @param clazz
     * @Description: 根据表达式和参数集合进行计算
     * @Author: chenhf
     * @Date: 2021/6/22 16:12
     * @return: java.lang.Object
     */
    private static Object exeScriptExpression(String eval, Map<String, Object> map,List<Class> definedStrategies,Class<?>... clazz) {
        JexlEngine engine = new JexlBuilder().create();
        JexlScript script = engine.createScript(eval);
        JexlContext context = new MapContext();
        definedStrategies.forEach(strategy->{
            try {
                Object o = strategy.newInstance();
                context.set(strategy.getSimpleName(),o);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        Arrays.asList(clazz).forEach(cal -> {
            context.set(cal.getSimpleName(),cal);
        });
        if (Objects.nonNull(map)) {
            map.forEach(context::set);
        }
        return  script.execute(context);
    }

    // 测试代码
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("FH_KPI000003", 1);
        map.put("LR_KPI000010", 2);
        map.put("FH_KPI000028", 3);
        map.put("tjxs", 4d);

//        String eval = "Test2。run(${eid})";
        String eval = "FH_KPI000003";
        List<Class> definedStrategies = new ArrayList<>();
        definedStrategies.add(Test2.class);

        Object test1 = exeScriptExpression(eval,map,definedStrategies, Math.class,BigDecimal.class);
        System.out.println(test1);

//        String a = "1";
//        Double aDouble = Double.valueOf(a);
//        System.out.println(aDouble);
//        System.out.println(new Test2().getDate(-1,12,31));
    }
}
